const root = '/'
const axios = require('axios')

// 判断元素类型
function toType(obj) {
	return {}.toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}

// 过滤参数中的null
function filterNull(obj) {
	for (var key in obj) {
		if (obj[key] === null) {
			delete obj[key]
		}
		if (toType(obj[key]) === 'string') {
			obj[key] = obj[key].trim()
		} else if (toType(obj[key]) === 'object') {
			obj[key] = filterNull(obj[key])
		} else if (toType(obj[key]) === 'array') {
			obj[key] = filterNull(obj[key])
		}
	}
	return obj
}


function apiAxios(method, url, params, success, failure) {
	if (params) {
		params = filterNull(params)
	}

	axios({
		method: method,
		url: url,
		data: method === 'POST' || method === 'PUT' ? params : null,
		params: method === 'GET' || method === 'DELETE' ? params : null,
		baseURL: root,
		// `withCredentials` 表示跨域请求时是否需要使用凭证
		withCredentials: false
	})
	.then(res => {
		success(res.data)
		return
	})
	.catch(error => {
		console.log(`error: ${error}`)
		failure(error)
		return
	})
}


export default {
	get: function(url, params, success, failure) {
		return apiAxios('GET', url, params, success, failure)
	},
	post: function(url, params, success, failure) {
		return apiAxios('POST', url, params, success, failure)
	},
	put: function(url, params, success, failure) {
		return apiAxios('PUT', url, params, success, failure)
	},
	delete: function(url, params, success, failure) {
		return apiAxios('DELETE', url, params, success, failure)
	}
}
